package com.ruoyi.web.community.service;
import com.ruoyi.config.BaiduFaceConfig;
import org.json.JSONObject;
import com.baidu.aip.face.AipFace;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import java.util.HashMap;
// FaceRecognitionService.java
@Service
public class FaceRecognitionService {

    private final AipFace aipFace;
    private final String groupId;
    private final SysUserMapper userMapper;

    public FaceRecognitionService(AipFace aipFace, BaiduFaceConfig config, SysUserMapper userMapper) {
        this.aipFace = aipFace;
        this.groupId = config.getGroupId();
        this.userMapper = userMapper;
    }

    // 人脸注册
    public String registerFace(String username, String phone, String base64Image) {
        // 1. 检测人脸
        JSONObject detectRes = detectFace(base64Image);
        if (!detectRes.has("result") || detectRes.getJSONObject("result").getInt("face_num") != 1) {
            throw new RuntimeException("未检测到人脸或检测到多张人脸");
        }

        // 2. 生成纯数字用户ID（使用时间戳）
        String userId = String.valueOf(System.currentTimeMillis());

        // 3. 添加到百度人脸库
        JSONObject addRes = aipFace.addUser(
                base64Image,
                "BASE64",
                groupId,
                userId,
                new HashMap<String, String>() {{
                    put("user_info", username + "|" + phone);
                    put("quality_control", "NORMAL");
                    put("liveness_control", "NORMAL");
                }}
        );

        if (addRes.has("error_code") && addRes.getInt("error_code") != 0) {
            throw new RuntimeException("添加人脸到人脸库失败: " + addRes.getString("error_msg"));
        }

        // 4. 保存到本地数据库
        SysUser user = new SysUser();
        user.setUserName(username);
        user.setPhonenumber(phone);
        user.setFaceUserId(userId); // 存储纯数字的百度用户ID
        userMapper.insertUser(user);

        return userId;
    }

    // 人脸登录
    public SysUser loginWithFace(String base64Image) {
        // 1. 检测人脸
        JSONObject detectRes = detectFace(base64Image);
        if (!detectRes.has("result") || detectRes.getJSONObject("result").getInt("face_num") != 1) {
            throw new RuntimeException("未检测到人脸或检测到多张人脸");
        }

        // 2. 在百度人脸库中搜索
        JSONObject searchRes = aipFace.search(
                base64Image,
                "BASE64",
                groupId,
                new HashMap<String, Object>() {{
                    put("quality_control", "LOW"); // 降低质量控制标准
                    put("liveness_control", "NONE"); // 不进行活体检测
                    put("max_user_num", 1);
                }}
        );

//        if (searchRes.has("error_code")) {
//            int errorCode = searchRes.getInt("error_code");
//            String errorMsg = searchRes.getString("error_msg");
//            // 针对错误码6的特殊处理
//            if (errorCode == 6) {
//                System.err.println("警告：未检测到人脸，可能需要调整图片质量");
//                // 可以选择返回默认结果或进行其他处理
//            }
//            throw new RuntimeException("人脸搜索失败: " + errorMsg);
//        }

        JSONObject result = searchRes.getJSONObject("result");
        if (result.getJSONArray("user_list").length() == 0) {
            throw new RuntimeException("未找到匹配的用户");
        }

        JSONObject userMatch = result.getJSONArray("user_list").getJSONObject(0);
        if (userMatch.getDouble("score") < 80) {
            throw new RuntimeException("人脸匹配度不足");
        }

        // 3. 获取百度用户ID并查询本地用户
        String userId = userMatch.getString("user_id");
        return userMapper.selectUserByFaceId(userId);
    }

    // 人脸检测
    private JSONObject detectFace(String base64Image) {
        return aipFace.detect(
                base64Image,
                "BASE64",
                new HashMap<String, Object>() {{
                    put("face_field", "age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type");
                    put("max_face_num", 1);
                }}
        );
    }
}
